package net.lovesrc.allin.biz;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Service
public class NotificationService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(2);

    public static final String LZQ_EMAIL = "504958845@qq.com";

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public void email(String to, String subject, String text) {
        if (StringUtils.isBlank(to)) {
            return;
        }
        try {
            MimeMessage msg = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(msg);
            helper.setFrom("504958845@qq.com");
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(text, true);
            this.email(msg);
        } catch (MessagingException e) {
            logger.error("Send " + text + " error", e);
        }
    }

    public void email(MimeMessage message) {

        try {
            javaMailSender.send(message);
        } catch (Exception e) {
            logger.error("Send Email error", e);
        }
    }

    public void syncEmail(String text) {

        this.syncEmail(NotificationService.LZQ_EMAIL, text);
    }

    public void syncEmail(String to, String text) {
        EXECUTOR_SERVICE.execute(() -> this.email(to, text, text));
    }

    public void oneEmailIn10Minutes(String text) {

        String cacheKey = "Email:" + text;
        if (redisTemplate.hasKey(cacheKey)) {
            return;
        }
        this.email(LZQ_EMAIL, text, text);
        redisTemplate.opsForValue().set(cacheKey, String.valueOf(System.currentTimeMillis()), 10, TimeUnit.MINUTES);
    }

}
